#include "app_common.h"
#include "log/log.h"
#include "sys/time.h"
#include "stdlib.h"
#include "string.h"

long app_common_getCurrentTime(void)
{
    struct timeval tv;

    gettimeofday(&tv, NULL);

    return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}


// [ a b ] "6162"
char* app_common_charsToHexstr(char *chars, int chars_len)
{
    char *hexstr = (char *)malloc(chars_len * 2 + 1);

    if(hexstr == NULL)
    {
        log_error("malloc hexstr failed");
        return NULL;
    }

    // for(int i = 0; i < chars_len; i++)
    // {
    //     sprintf(hexstr + i * 2, "%02x", chars[i]);
    // }

    // //hexstr[chars_len * 2] = 'a';
    // log_debug("hexstr: %s", hexstr);

    for (int i = 0; i < chars_len; i++) {
        // 使用 snprintf 确保不会发生缓冲区溢出
        snprintf(hexstr + i * 2, 3, "%02x", (unsigned char)chars[i]);
    }

    // 确保字符串正确终止（虽然snprintf已经保证，但这是额外保障）
    hexstr[chars_len * 2] = '\0';

    return hexstr;
}

// "6162" [a b]
char* app_common_hexstrToChars(char *hexstr, int *s_chars_len)
{

    *s_chars_len = strlen(hexstr) / 2;
    char *chars = (char *)malloc(*s_chars_len);

    if(chars == NULL)
    {
        log_error("malloc chars failed");
        return NULL;
    }

    for(int i = 0; i < *s_chars_len; i++)
    {
        sscanf(hexstr + i * 2, "%2x", (unsigned int *)(chars + i));
    }

    return chars;
}

